"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import AdminPolls from "@/components/admin-polls"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { CheckCircle2, WifiOff, AlertCircle } from "lucide-react"
import { createPoll } from "@/lib/db"
import { isOfflineMode, getOfflineModePreference, setOfflineModePreference } from "@/lib/db"
import { getAboutContent, updateAboutContent } from "@/lib/db-sqlite"
import SampleDataNotice from "@/components/sample-data-notice"

export default function AdminPage() {
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [authenticated, setAuthenticated] = useState(false)
  const [authError, setAuthError] = useState<string | null>(null)
  const [title, setTitle] = useState("")
  const [description, setDescription] = useState("")
  const [options, setOptions] = useState(["", ""])
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [offline, setOffline] = useState(false)
  const [offlinePreference, setOfflinePreference] = useState(false)
  const [activeTab, setActiveTab] = useState("create")
  
  // 关于页面管理状态
  const [aboutTitle, setAboutTitle] = useState("")
  const [aboutDescription, setAboutDescription] = useState("")
  const [aboutIntro, setAboutIntro] = useState("")
  const [aboutFeatures, setAboutFeatures] = useState<string[]>([])
  const [aboutPrivacy, setAboutPrivacy] = useState("")
  const [aboutInstructions, setAboutInstructions] = useState<string[]>([])
  const [aboutLoading, setAboutLoading] = useState(false)
  const [aboutSuccess, setAboutSuccess] = useState(false)
  const [aboutError, setAboutError] = useState<string | null>(null)
  const router = useRouter()

  // 初始化离线状态和加载关于页面内容
  useEffect(() => {
    setOffline(isOfflineMode())
    setOfflinePreference(getOfflineModePreference())

    // 监听网络状态变化
    const handleOnline = () => setOffline(false)
    const handleOffline = () => setOffline(true)

    window.addEventListener("online", handleOnline)
    window.addEventListener("offline", handleOffline)

    // 检查本地存储中的认证状态
    const isAuth = localStorage.getItem("adminAuthenticated") === "true"
    setAuthenticated(isAuth)
    
    // 如果已认证，加载关于页面内容
    if (isAuth) {
      loadAboutContent()
    }

    return () => {
      window.removeEventListener("online", handleOnline)
      window.removeEventListener("offline", handleOffline)
    }
  }, [])

  const handleAuthenticate = async (e: React.FormEvent) => {
    e.preventDefault()
    setAuthError(null)

    try {
      const response = await fetch("/api/auth", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password }),
      })

      const data = await response.json()

      if (!response.ok) {
        setAuthError(data.error || "认证失败")
        return
      }

      setAuthenticated(true)
      // 保存认证状态到本地存储
      localStorage.setItem("adminAuthenticated", "true")
    } catch (error: any) {
      console.error("Authentication error:", error)
      setAuthError(error.message || "认证失败，请稍后再试")
    }
  }

  const handleAddOption = () => {
    setOptions([...options, ""])
  }

  const handleOptionChange = (index: number, value: string) => {
    const newOptions = [...options]
    newOptions[index] = value
    setOptions(newOptions)
  }

  const handleRemoveOption = (index: number) => {
    if (options.length <= 2) return
    const newOptions = [...options]
    newOptions.splice(index, 1)
    setOptions(newOptions)
  }

  const handleOfflineModeToggle = (checked: boolean) => {
    setOfflinePreference(checked)
    setOfflineModePreference(checked)
  }

  const handleCreatePoll = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)

    if (!title.trim()) {
      setError("请输入投票标题")
      return
    }

    const filteredOptions = options.filter((opt) => opt.trim())
    if (filteredOptions.length < 2) {
      setError("至少需要两个有效选项")
      return
    }

    setLoading(true)

    try {
      await createPoll(title.trim(), description, filteredOptions)

      // 重置表单
      setTitle("")
      setDescription("")
      setOptions(["", ""])

      // 显示成功消息
      setSuccess(true)
      setTimeout(() => setSuccess(false), 3000)

      // 切换到管理标签页
      setActiveTab("manage")
    } catch (error: any) {
      console.error("Error creating poll:", error)
      setError(error.message || "创建失败，请稍后再试")
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    try {
      await fetch("/api/auth", {
        method: "DELETE",
      })

      setAuthenticated(false)
      localStorage.removeItem("adminAuthenticated")
    } catch (error) {
      console.error("Logout error:", error)
    }
  }
  
  // 加载关于页面内容
  const loadAboutContent = async () => {
    try {
      const response = await fetch("/api/about", {
        method: "GET",
      })
      
      if (!response.ok) {
        throw new Error("获取关于页面内容失败")
      }
      
      const data = await response.json()
      
      if (data && data.content) {
        setAboutTitle(data.title || "")
        setAboutDescription(data.description || "")
        
        // 解析JSON内容
        const content = JSON.parse(data.content)
        setAboutIntro(content.intro || "")
        setAboutFeatures(content.features || [])
        setAboutPrivacy(content.privacy || "")
        setAboutInstructions(content.instructions || [])
      }
    } catch (error) {
      console.error("Error loading about content:", error)
    }
  }
  
  // 保存关于页面内容
  const handleSaveAboutContent = async (e: React.FormEvent) => {
    e.preventDefault()
    setAboutError(null)
    
    if (!aboutTitle.trim()) {
      setAboutError("请输入标题")
      return
    }
    
    setAboutLoading(true)
    
    try {
      // 构建内容JSON
      const contentJson = JSON.stringify({
        intro: aboutIntro,
        features: aboutFeatures.filter(item => item.trim()),
        privacy: aboutPrivacy,
        instructions: aboutInstructions.filter(item => item.trim())
      })
      
      const response = await fetch("/api/about", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title: aboutTitle.trim(),
          description: aboutDescription.trim(),
          content: contentJson
        }),
      })
      
      if (!response.ok) {
        throw new Error("保存失败")
      }
      
      // 显示成功消息
      setAboutSuccess(true)
      setTimeout(() => setAboutSuccess(false), 3000)
    } catch (error: any) {
      console.error("Error saving about content:", error)
      setAboutError(error.message || "保存失败，请稍后再试")
    } finally {
      setAboutLoading(false)
    }
  }
  
  // 添加特性
  const handleAddFeature = () => {
    setAboutFeatures([...aboutFeatures, ""])
  }
  
  // 修改特性
  const handleFeatureChange = (index: number, value: string) => {
    const newFeatures = [...aboutFeatures]
    newFeatures[index] = value
    setAboutFeatures(newFeatures)
  }
  
  // 删除特性
  const handleRemoveFeature = (index: number) => {
    const newFeatures = [...aboutFeatures]
    newFeatures.splice(index, 1)
    setAboutFeatures(newFeatures)
  }
  
  // 添加使用说明
  const handleAddInstruction = () => {
    setAboutInstructions([...aboutInstructions, ""])
  }
  
  // 修改使用说明
  const handleInstructionChange = (index: number, value: string) => {
    const newInstructions = [...aboutInstructions]
    newInstructions[index] = value
    setAboutInstructions(newInstructions)
  }
  
  // 删除使用说明
  const handleRemoveInstruction = (index: number) => {
    const newInstructions = [...aboutInstructions]
    newInstructions.splice(index, 1)
    setAboutInstructions(newInstructions)
  }

  if (!authenticated) {
    return (
      <div className="container mx-auto px-4 py-10 flex justify-center items-center min-h-[80vh]">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle>管理员登录</CardTitle>
            <CardDescription>请输入管理员用户名和密码以继续</CardDescription>
          </CardHeader>
          <form onSubmit={handleAuthenticate}>
            <CardContent>
              <div className="grid w-full items-center gap-4">
                <div className="flex flex-col space-y-1.5">
                  <Label htmlFor="username">用户名</Label>
                  <Input
                    id="username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    placeholder="输入用户名"
                    required
                  />
                </div>
                <div className="flex flex-col space-y-1.5">
                  <Label htmlFor="password">密码</Label>
                  <Input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="输入密码"
                    required
                  />
                </div>
                {authError && (
                  <Alert variant="destructive">
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription>{authError}</AlertDescription>
                  </Alert>
                )}
              </div>
            </CardContent>
            <CardFooter>
              <Button type="submit" className="w-full">
                登录
              </Button>
            </CardFooter>
          </form>
        </Card>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-10">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">管理员控制台</h1>
        <Button variant="outline" onClick={handleLogout}>
          退出登录
        </Button>
      </div>

      <SampleDataNotice />

      {/* 离线模式状态 */}
      {offline && (
        <Alert className="mb-4 bg-yellow-50 border-yellow-200">
          <WifiOff className="h-4 w-4 text-yellow-600" />
          <AlertDescription className="text-yellow-800">您当前处于离线状态。部分功能可能不可用。</AlertDescription>
        </Alert>
      )}

      {/* 离线模式切换 */}
      <div className="flex items-center space-x-2 mb-4">
        <Switch id="offline-mode" checked={offlinePreference} onCheckedChange={handleOfflineModeToggle} />
        <Label htmlFor="offline-mode">离线模式</Label>
        <span className="text-sm text-gray-500 ml-2">
          {offlinePreference ? "已启用 - 使用本地数据" : "已禁用 - 使用在线数据"}
        </span>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="mb-4">
          <TabsTrigger value="create">创建投票</TabsTrigger>
          <TabsTrigger value="manage">管理投票</TabsTrigger>
          <TabsTrigger value="about">关于页面管理</TabsTrigger>
        </TabsList>

        <TabsContent value="create">
          <Card>
            <CardHeader>
              <CardTitle>创建新投票</CardTitle>
              <CardDescription>设置投票问题和选项</CardDescription>
            </CardHeader>
            {success && (
              <Alert className="mx-6 mb-4 bg-green-50 text-green-800 border-green-200">
                <CheckCircle2 className="h-4 w-4 text-green-600" />
                <AlertDescription>投票创建成功！</AlertDescription>
              </Alert>
            )}
            {error && (
              <Alert className="mx-6 mb-4 bg-red-50 border-red-200">
                <AlertCircle className="h-4 w-4 text-red-600" />
                <AlertDescription className="text-red-800">{error}</AlertDescription>
              </Alert>
            )}
            <form onSubmit={handleCreatePoll}>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="title">投票标题</Label>
                  <Input
                    id="title"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    placeholder="输入投票标题"
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">描述（可选）</Label>
                  <Textarea
                    id="description"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="输入投票描述"
                    rows={3}
                  />
                </div>

                <div className="space-y-3">
                  <Label>选项</Label>
                  {options.map((option, index) => (
                    <div key={index} className="flex gap-2">
                      <Input
                        value={option}
                        onChange={(e) => handleOptionChange(index, e.target.value)}
                        placeholder={`选项 ${index + 1}`}
                        required
                      />
                      {options.length > 2 && (
                        <Button type="button" variant="outline" size="icon" onClick={() => handleRemoveOption(index)}>
                          ✕
                        </Button>
                      )}
                    </div>
                  ))}
                  <Button type="button" variant="outline" onClick={handleAddOption}>
                    添加选项
                  </Button>
                </div>
              </CardContent>
              <CardFooter>
                <Button type="submit" disabled={loading}>
                  {loading ? "创建中..." : "创建投票"}
                </Button>
              </CardFooter>
            </form>
          </Card>
        </TabsContent>

        <TabsContent value="manage">
          <AdminPolls />
        </TabsContent>
        
        <TabsContent value="about">
          <Card>
            <CardHeader>
              <CardTitle>编辑"关于"页面内容</CardTitle>
              <CardDescription>修改网站"了解更多"页面显示的内容</CardDescription>
            </CardHeader>
            {aboutSuccess && (
              <Alert className="mx-6 mb-4 bg-green-50 text-green-800 border-green-200">
                <CheckCircle2 className="h-4 w-4 text-green-600" />
                <AlertDescription>内容保存成功！</AlertDescription>
              </Alert>
            )}
            {aboutError && (
              <Alert className="mx-6 mb-4 bg-red-50 border-red-200">
                <AlertCircle className="h-4 w-4 text-red-600" />
                <AlertDescription className="text-red-800">{aboutError}</AlertDescription>
              </Alert>
            )}
            <form onSubmit={handleSaveAboutContent}>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="aboutTitle">页面标题</Label>
                  <Input
                    id="aboutTitle"
                    value={aboutTitle}
                    onChange={(e) => setAboutTitle(e.target.value)}
                    placeholder="输入页面标题"
                    required
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="aboutDescription">页面描述</Label>
                  <Input
                    id="aboutDescription"
                    value={aboutDescription}
                    onChange={(e) => setAboutDescription(e.target.value)}
                    placeholder="输入页面描述"
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="aboutIntro">系统介绍</Label>
                  <Textarea
                    id="aboutIntro"
                    value={aboutIntro}
                    onChange={(e) => setAboutIntro(e.target.value)}
                    placeholder="输入系统介绍内容"
                    rows={4}
                  />
                </div>
                
                <div className="space-y-3">
                  <Label>主要功能</Label>
                  {aboutFeatures.map((feature, index) => (
                    <div key={index} className="flex gap-2">
                      <Input
                        value={feature}
                        onChange={(e) => handleFeatureChange(index, e.target.value)}
                        placeholder={`功能 ${index + 1}`}
                      />
                      <Button type="button" variant="outline" size="icon" onClick={() => handleRemoveFeature(index)}>
                        ✕
                      </Button>
                    </div>
                  ))}
                  <Button type="button" variant="outline" onClick={handleAddFeature}>
                    添加功能
                  </Button>
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="aboutPrivacy">隐私保护</Label>
                  <Textarea
                    id="aboutPrivacy"
                    value={aboutPrivacy}
                    onChange={(e) => setAboutPrivacy(e.target.value)}
                    placeholder="输入隐私保护内容"
                    rows={4}
                  />
                </div>
                
                <div className="space-y-3">
                  <Label>使用说明</Label>
                  {aboutInstructions.map((instruction, index) => (
                    <div key={index} className="flex gap-2">
                      <Input
                        value={instruction}
                        onChange={(e) => handleInstructionChange(index, e.target.value)}
                        placeholder={`说明 ${index + 1}`}
                      />
                      <Button type="button" variant="outline" size="icon" onClick={() => handleRemoveInstruction(index)}>
                        ✕
                      </Button>
                    </div>
                  ))}
                  <Button type="button" variant="outline" onClick={handleAddInstruction}>
                    添加说明
                  </Button>
                </div>
              </CardContent>
              <CardFooter>
                <Button type="submit" disabled={aboutLoading}>
                  {aboutLoading ? "保存中..." : "保存更改"}
                </Button>
              </CardFooter>
            </form>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
